/**
 * 好会员接口相关
 * @author ytl
 */

import Qs from 'qs'
import axios from 'axios';
import { INTERACE_HHY_BASE_URL } from 'components/api/index-local';
import {setSessionStorageItem, getSessionStorageItem} from 'components/api/utils';

// 接口自定义code状态
export const RESPONSE_CODE_SUCCESS = 'SUCCESS';
export const RESPONSE_CODE_FAIL = 'FAIL';

// 客户端类型
export const CLIENT_WECHAT = 'WECHAT'    // 微信
export const CLIENT_ALIPAY = 'ALIPAY'    // 支付宝

// 会员类型
export const USER_LEVEL_FANS = 'FANS';  // 粉丝
export const USER_LEVEL_REGISTE = 'REGISTE';  // 注册会员
export const USER_LEVEL_PREPAID = 'PREPAID';  // 储值会员会员

/**
 * 创建axios实例
 * @return {axios}
 */
export function createHttp () {
  let $httpHhy = axios.create({
    baseURL: INTERACE_HHY_BASE_URL,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
    // timeout: 5000
  });

  $httpHhy.interceptors.response.use(res => {
    return res.data;
  }, err => {
    console.log(err);
    return Promise.reject(err);
  });
  return $httpHhy;
}

/**
 * 获取code url
 * @param params
 * @return {String}
 */
export function getAuthCodeUrl (params, backUrl) {
  let {
    branchId,
    clientType,
    businessType,
    authId = ''
  } = params;

  let url = INTERACE_HHY_BASE_URL + '/get-code/branch_id/' + branchId +
    '/client_type/' + clientType +
    '/business_type/' + businessType +
    '/auth_id/' + authId;
  url += '?back_uri=' + encodeURIComponent(backUrl);
  return url;
}

/**
 * 初始化会员信息
 * @param {Object} params 请求参数
 * @param {Object} authQuery 微信/支付宝授权信息（code、state、appid）
 * @return {Promise}
 */
export function initUserIdentity (params, authQuery) {
  let {
    branchId = 0,
    clientType,
    businessType,
    authId = '',
    tableId = 0
  } = params;

  let url = '/user/branch_id/' + branchId +
    '/client_type/' + clientType +
    '/business_type/' + businessType +
    '/auth_id/' + authId;

  url += '?' + Qs.stringify(authQuery);

  let $httpHhy = createHttp();

  $httpHhy.interceptors.response.use(res => {
    setSessionStorageItem('userIdentity', {
      businessType: businessType,
      orgId: res.orgId,
      uid: res.uid,
      authId: res.authId,
      branchId: branchId,
      tableId: tableId,
      userId: res.id,
      showname: res.showname,
      mobile: res.mobile,
      levelType: res.levelType
    });
    return res;
  }, err => {
    console.log(err);
    return Promise.reject(err);
  });

  return $httpHhy.get(url);
}

/**
 * 获取当前会员信息
 * @param key 会员信息key值，null时返回会员所有信息
 * @returns Object|string|null
 */
export function getUserIdentity (key = null) {
  let userIdentity = getSessionStorageItem('userIdentity');
  if (key === null) {
    return userIdentity;
  }
  return userIdentity ? userIdentity[key] : null;
}

/**
 * 更新当前会员信息
 * @param key 要更新的key
 * @param value 要更新的值
 */
export function updateUserIdentity (key, value) {
  let userIdentity = getUserIdentity();
  userIdentity[key] = value;
  setSessionStorageItem('userIdentity', userIdentity);
}

/**
 * 根据userId获取会员信息（从服务器查询）
 * @return {Promise}
 */
export function getUserInfoByUserId () {
  let userIdentity = getUserIdentity();
  let url = '/user/uid/' + userIdentity.uid + '/user_id/' + userIdentity.userId;
  let $httpHhy = createHttp();
  return $httpHhy.get(url);
}

/**
 * 获取会员可用卡券
 * @return {Promise}
 */
export function getUsercardList () {
  let userIdentity = getUserIdentity();
  let url = '/usercard/uid/' + userIdentity.uid +
    '/user_id/' + userIdentity.userId +
    '/branch_id/' + userIdentity.branchId;
  let $httpHhy = createHttp();
  return $httpHhy.get(url);
}

/**
 * 获取低分抵扣比例
 * @return {Promise}
 */
export function getPointsConfig () {
  let uid = getUserIdentity('uid');
  let url = '/points-config/uid/' + uid;
  let $httpHhy = createHttp();
  return $httpHhy.get(url);
}

/**
 * 发送验证短信
 * @param mobile
 * @return {Promise}
 */
export function sendSmsCode (mobile) {
  let userIdentity = getUserIdentity();
  let url = '/sms/send-sms-code';
  let $httpHhy = createHttp();
  return $httpHhy.post(url, {
    auth_id: userIdentity.authId,
    user_id: userIdentity.userId,
    mobile: mobile
  });
}

/**
 * 更新会员信息
 * @param params Object {
 *    mobile: mobile,
 *    mobileCode: mobileCode,
 *    name: name
 *  }
 * @return {Promise}
 */
export function updateUserInfo (params) {
  let {mobile = '', mobileCode = '', name = ''} = params;
  let userIdentity = getUserIdentity();
  let url = '/user/auth_id/' + userIdentity.authId + '/user_id/' + userIdentity.userId;
  console.log(params)
  let $httpHhy = createHttp();
  $httpHhy.interceptors.response.use(res => {
    if (res.code === RESPONSE_CODE_SUCCESS) {
      updateUserIdentity('mobile', mobile);
    }
    return res;
  }, err => {
    console.log(err);
    return Promise.reject(err);
  });
  console.log('更新会员信息')
  console.log(mobileCode);
  return $httpHhy.patch(url, {
    mobile: mobile,
    mobile_code: mobileCode,
    name: name
  });
}

/**
 * 添加配送地址
 * @param params
 * @return {Promise}
 */
export function createUserShippingAddress (params) {
  let userIdentity = getUserIdentity();
  let url = '/user-shipping-address';
  console.log(params);
  console.log('新增地址');
  let $httpHhy = createHttp();
  return $httpHhy.post(url, {
    uid: userIdentity.uid,
    user_id: userIdentity.userId,
    username: params.username,
    sex: params.sex,
    mobile: params.mobile,
    address: params.address,
    detail: params.detail,
    longitude: params.longitude,
    latitude: params.latitude,
    is_default: params.is_default
  });
}

/**
 * 修改配送地址
 * @param params
 * @return {Promise}
 */
export function updateUserShippingAddress (params) {
  let userIdentity = getUserIdentity();
  let url = '/user-shipping-address/id/' + params.id;
  let $httpHhy = createHttp();
  return $httpHhy.put(url, {
    id: params.id,
    uid: userIdentity.uid,
    user_id: userIdentity.userId,
    username: params.username,
    sex: params.sex,
    mobile: params.mobile,
    address: params.address,
    detail: params.detail,
    longitude: params.longitude,
    latitude: params.latitude,
    is_default: params.is_default
  });
}

/**
 * 删除配送地址
 * @param id
 * @return {Promise}
 */
export function deleteUserShippingAddress (id) {
  let userIdentity = getUserIdentity();
  let url = '/user-shipping-address/uid/' + userIdentity.uid +
    '/user_id/' + userIdentity.userId +
    '/id/' + id;
  let $httpHhy = createHttp();
  return $httpHhy.delete(url);
}

/**
 * 查询配送地址列表
 * @param isDefault
 * @return {Promise}
 */
export function getUserShippingAddressList (isDefault = '') {
  let userIdentity = getUserIdentity();
  let url = '/user-shipping-address/uid/' + userIdentity.uid +
    '/user_id/' + userIdentity.userId +
    '/is_default/' + isDefault;
  let $httpHhy = createHttp();
  return $httpHhy.get(url);
}
